import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import commonJs from "@/tool/common.js";
import { Dialog } from "mand-mobile";

Vue.use(Router);
const login = () => import("./views/login/index.vue");
const home = () => import("./views/home/index.vue");
const alwaysRaise = () => import("./views/alwaysRaise/index.vue");
const onTheDayToRaise = () => import("./views/onTheDayToRaise/index.vue");
const cashValue = () => import("./views/cashValue/index.vue");

let router = new Router({
  routes: [
    {
      path: "/",
      name: "login",
      component: login,
      meta: { name: "登录" }
    },
    {
      path: "/home",
      name: "home",
      component: home,
      meta: {
        name: "好融艺平台数据",
        needLogin: true
      }
    },
    {
      path: "/always-raise",
      name: "alwaysRaise",
      component: alwaysRaise,
      meta: {
        name: "募资总金额",
        needLogin: true
      }
    },
    {
      path: "/on-the-day-to-raise",
      name: "onTheDayToRaise",
      component: onTheDayToRaise,
      meta: {
        name: "当日募资金额",
        needLogin: true
      }
    },
    {
      path: "/recharge",
      name: "recharge",
      component: cashValue,
      meta: {
        name: "会员充值明细",
        needLogin: true
      }
    },
    {
      path: "/withdraw",
      name: "withdraw",
      component: cashValue,
      meta: {
        name: "会员提现明细",
        needLogin: true
      }
    }
  ]
});
export default router;
router.beforeEach(function(to, from, next) {
  let validate = true;
  let readyPromise = null;
  let readyPromiseRS = null;
  readyPromise = new Promise(resolve => {
    readyPromiseRS = resolve;
  });
  if (to.matched[0].name === "index") {
    // 只在刷新的时候获取sessionStorage的state
    if (from.matched.length === 0) {
      let state = window.sessionStorage.getItem("state");
      if (state) {
        store.replaceState(JSON.parse(state));
      }
      commonJs.getInfo(() => {
        readyPromiseRS();
      });
    } else {
      readyPromiseRS();
    }
  } else {
    readyPromiseRS();
  }
  readyPromise.then(() => {
    if (to.meta.needLogin) {
      if (!store.state.isLogin) {
        validate = false;
        Dialog.confirm({
          title: "未登录",
          content: "亲爱的用户：您尚未进行登录，请前去登录",
          confirmText: "去登录",
          onConfirm: () => {
            router.push({ name: "login" });
          }
        });
      }
    }
    if (validate) {
      store.dispatch("changeActiveMenu", to.meta.activeHeaderMenu);
      store.dispatch("changeCurrentRouterName", to.meta.name);
    }
    if (validate) {
      next();
    }
  });
});
